package com.elong.android.specialhouse.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.elong.android.specialhouse.ApartmentApplication;
import com.elong.android.specialhouse.IConfig;
import com.elong.android.specialhouse.db.DB;
import com.elong.android.specialhouse.db.DatabaseHelper;

import java.util.HashMap;

/**
 * 
 * @ClassName: CacheHelper
 * @Description: 数据库方式存储缓存数据
 * @author: hongjun guo
 * @date:2014-2-27 下午2:37:31
 */
public class CacheHelper {
	private static HashMap<String, CityDistrict> s_cityDistricts = new HashMap<String, CityDistrict>();

	/**
	 * 
	 * @Title: loadCache
	 * @Description: 从数据库加载缓存数据
	 * @param
	 * @return void
	 * @throws
	 */
	public final static void loadCache() {
		DatabaseHelper databaseHelper = new DatabaseHelper(ApartmentApplication.getContext(), DB.DATABASE_NAME, null, DB.VERSION);
		SQLiteDatabase db = databaseHelper.getReadableDatabase();
		Cursor c = db.rawQuery("SELECT * FROM " + DB.TABLE_CITY_DISTRICTS, null);
		if (s_cityDistricts == null) {
			s_cityDistricts = new HashMap<String, CityDistrict>();
		}
		try {
			boolean hasData = c.moveToFirst();
			if (hasData) {
				while (true) {
					CityDistrict item = new CityDistrict();
					item.fromCursor(c);
					s_cityDistricts.put(item.m_city, item);

					item = null;
					if (c.isLast()) {
						break;
					}
					c.moveToNext();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			c.close();
			db.close();
			c = null;
			db = null;
			databaseHelper = null;
		}
	}

	/**
	 * 
	 * @Title: getCityDistricts
	 * @Description: 获取指定城市的行政区划信息
	 * @param @param city 城市名称
	 * @param @return
	 * @return String
	 * @throws
	 */
	public final static String getCityDistricts(String city) {
		if (s_cityDistricts == null || s_cityDistricts.size() == 0) {
			loadCache();
		}

		if (s_cityDistricts != null && s_cityDistricts.containsKey(city)) {
			CityDistrict data = s_cityDistricts.get(city);
			if (System.currentTimeMillis() - data.m_lastModified < IConfig.CITY_DISTRICTDATA_UPDATEPERIOD) {
				return data.m_data;
			}
		}
		return null;
	}

	/**
	 * 
	 * @Title: cacheCityDistrict
	 * @Description: 缓存制定城市的数据
	 * @param @param context
	 * @param @param city
	 * @param @param data
	 * @return void
	 * @throws
	 */
	public final static void cacheCityDistrict(Context context, String city, String data) {

		if (s_cityDistricts == null) {
			loadCache();
		}

		boolean needUpdate = !s_cityDistricts.containsKey(city);
		if (!needUpdate) {
			needUpdate = System.currentTimeMillis() - s_cityDistricts.get(city).m_lastModified > IConfig.CITY_DISTRICTDATA_UPDATEPERIOD;
		}

		if (needUpdate) {
			boolean isNew = false;
			CityDistrict item = s_cityDistricts.get(city);
			if (item == null) {
				isNew = true;
				item = new CityDistrict();
			}

			item.m_city = city;
			item.m_data = data;
			item.m_lastModified = System.currentTimeMillis();

			s_cityDistricts.put(city, item);

			DatabaseHelper databaseHelper = new DatabaseHelper(context, DB.DATABASE_NAME, null, DB.VERSION);
			SQLiteDatabase db = databaseHelper.getWritableDatabase();
			if (db != null) {
				item.save2Database(db, isNew);
				db.close();
			}
		}
	}

	/**
	 * 
	 * @Title: cacheGrouponCityDistrict
	 * @Description: 缓存城市的行政区划和商圈信息到本地数据库
	 * @param @param context
	 * @param @param city
	 * @param @param data
	 * @return void
	 * @throws
	 */
	public final static void cacheGrouponCityDistrict(Context context, String city, String data) {
		boolean needUpdate = !s_cityDistricts.containsKey(city);
		if (!needUpdate) {
			needUpdate = System.currentTimeMillis() - s_cityDistricts.get(city).m_lastModified > IConfig.GROUPON_CITY_DISTRICTDATA_UPDATEPERIOD;
		}

		if (needUpdate) {
			boolean isNew = false;
			CityDistrict item = s_cityDistricts.get(city);
			if (item == null) {
				isNew = true;
				item = new CityDistrict();
			}

			item.m_city = city;
			item.m_data = data;
			/*
			 * if(districts != null) { item.m_districts = districts; }
			 * if(commercialArea != null) { item.m_commercialAreas =
			 * commercialArea; }
			 */
			item.m_lastModified = System.currentTimeMillis();
			s_cityDistricts.put(city, item);

			DatabaseHelper databaseHelper = new DatabaseHelper(context, DB.DATABASE_NAME, null, DB.VERSION);
			SQLiteDatabase db = databaseHelper.getWritableDatabase();
			if (db != null) {
				item.save2Database(db, isNew);
				db.close();
			}

			item = null;
		}
	}

	/**
	 * 
	 * @ClassName: CityDistrict
	 * @Description: 城市行政区,商圈等预缓存的区域信息
	 * @author: hongjun guo
	 * @date:2014-2-27 下午2:39:05
	 */
	private static class CityDistrict {
		String m_city;
		String m_data;
		long m_lastModified;

		// String m_districts;
		// String m_commercialAreas;

		/**
		 * 
		 * @Title: fromCursor
		 * @Description: 数据库数据转化成java对象
		 * @param @param c
		 * @return void
		 * @throws
		 */
		public void fromCursor(Cursor c) {
			m_city = c.getString(DB.COLINDEX_CITY);
			m_lastModified = c.getLong(DB.COLINDEX_LASTMODIFIED);
			m_data = c.getString(DB.COLINDEX_DATA);
			// m_districts = c.getString(DB.COLINDEX_DISTRICT);
			// m_commercialAreas = c.getString(DB.COLINDEX_COMMERCIALAREA);
		}

		/**
		 * @Title: save2Database
		 * @Description: 保存数据到数据库
		 * @param @param db
		 * @param @param isNew
		 * @return void
		 * @throws
		 */
		public void save2Database(SQLiteDatabase db, boolean isNew) {
			ContentValues values = new ContentValues();
			values.put(DB.COL_CITY, m_city);
			values.put(DB.COL_LASTMODIFIED, m_lastModified);
			values.put(DB.COL_DATA, m_data);
			// values.put(DB.COL_DISTRICTS, m_districts);
			// values.put(DB.COL_COMMERCIALAREA, m_commercialAreas);
			if (isNew) {
				db.insert(DB.TABLE_CITY_DISTRICTS, null, values);
			} else {
				db.update(DB.TABLE_CITY_DISTRICTS, values, DB.COL_CITY + "=?", new String[] { m_city });
			}
			values = null;
			// db.delete(DB.TABLE_CITY_DISTRICTS, whereClause, whereArgs);
		}
	}
}
